'use strict'


let nunjucks = require('nunjucks');



// 实例化 env 环境 用于渲染模板
function creatEnv(path, options) {
    path = path || 'views'
    options = options || {}
    let
        envOption = {
            'watch': options.watch === undefined ? true : options.watch,
            'autoescape': options.autoescape === undefined ? true : options.autoescape,
            'noCache': options.noCache === undefined ? true : options.noCache,
            'throwOnUndefined': options.throwOnUndefined === undefined ? true : options.throwOnUndefined
        },
        env = nunjucks.configure(path, envOption);

    return env
};


// 暴露模块 并重构 cxt.render() 方法
module.exports = async (ctx, next) => {
    ctx.render = function (view,model) {
        let env = creatEnv();
        ctx.body = env.render(view,model);
    };
    await next();
};